<template>
    <el-card shadow="hover" style="height: 100%; width: 100%; margin-left: 10px; overflow: scroll">
        <el-tabs v-model="tab" tab-position="top" style="margin-left: 20px">
            <el-tab-pane label="菜单权限" name="menuPower">
                <el-tree ref="menu" :check-strictly="checkStrictly" :default-checked-keys="data.checked" node-key="id"
                    :data="menu.list" :props="menu.props" :render-content="renderTreeNodeContent" show-checkbox
                    class="fixed-height-tree">
                </el-tree>
            </el-tab-pane>
            <el-tab-pane label="数据权限" name="dataPower">
                <data-permission ref="dataPower" v-model="staffDataPermission"></data-permission>
            </el-tab-pane>
        </el-tabs>
        <div style="
				width: 100%;
				height: 70px;
				position: absolute;
				bottom: 0;
				left: 10px;
				border-top: 0px solid #e8e8e8;
				padding-top: 10px;
			">
            <el-button style="margin-left: 30px" @click="close()">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
            <el-popconfirm v-if="mode != 'show' && staffDataPermission.id != 0 && !isMultiply && tab == 'dataPower'"
                title="确定要删除吗？" @confirm="del()">
                <template #reference>
                    <el-button type="primary" :loading="delLoading">删 除</el-button>
                </template>
            </el-popconfirm>

        </div>
    </el-card>

    <el-drawer v-model="dialog.dataPermission" :size="500" :title="permissionTitle" custom-class="drawerBG"
        direction="rtl" destroy-on-close>
        <dataPermissionDialog v-if="dialog.dataPermission" ref="dataPermissionDialog" @success="handleSaveSuccess"
            @closed="dialog.dataPermission = false"></dataPermissionDialog>
    </el-drawer>
</template>

<script>
import editSvg from '@/assets/icons/EditGrey.vue'
import editSvgYellow from '@/assets/icons/EditYellow.vue'

import dataPermission from './components/dataPermission.vue'
import dataPermissionDialog from './dataPermissionDialog.vue'

export default {
    emits: ['success', 'closed'],
    props: {},
    components: {
        editSvg,
        editSvgYellow,
        dataPermission,
        dataPermissionDialog
    },
    data() {
        return {
            dialog: {
                dataPermission: false
            },
            visible: false,
            isSaveing: false,
            tab: 'menuPower',
            menu: {
                list: [],
                checked: [1, 2],
                props: {
                    label: (data) => {
                        return data.meta.title
                    }
                }
            },
            data: {
                dataPower: 0,
                list: [],
                checked: [],
                props: {},
                rule: '',
                staffId: ''
            },
            dataPowerOptions: [],
            checkStrictly: true,
            permissionTitle: '权限设置',
            accountLoading: false,
            accountFilterText: '',
            accountList: [],
            staffDataPermission: {
                id: 0,
                area: [],
                province: [],
                city: [],
                custom: []
                // businessScenario: ''
            },
            isMultiply: false,
            staffIds: [],
            delLoading: false
        }
    },
    mounted() {
        // this.getMenu()
        // this.getDept()
    },
    methods: {
        close() {
            this.$emit('closed')
        },
        async open(data, isMultiply) {
            let _this = this
            setTimeout(function () {
                _this.checkStrictly = false
            }, 1000)

            await this.getMenu()
            this.isMultiply = isMultiply
            if (isMultiply) {
                //是批量权限设置
                this.staffIds = data.map((item) => {
                    return item.id
                })
            } else {
                this.data.staffId = data.id
                //根据账户ID查询菜单权限
                var res = await this.$API.basic.staff.powerByStaffId.post({ data: { staffId: data.id } })
                this.data.checked = []
                if (res && res.code == 0) {
                    const menuMap = this.buildMenuMap(this.menu.list, new Map());
                    res.data.forEach((item) => {
                        this.data.checked.push(item.id)
                        if (menuMap.has(item.id)) {
                            menuMap.get(item.id).editStatus = item.editStatus;
                        }
                    })
                }
                //根据账户ID查询数据权限
                var res1 = await this.$API.basic.staff.queryDataPower.post({ data: { staffId: data.id } })
                if (res1 && res1.code == 0 && res1.data) {
                    // this.staffDataPermission = res1.data
                    console.log(res1.data)
                    this.staffDataPermission.id = res1.data.id ? res1.data.id : 0
                    this.staffDataPermission.area = res1.data.area ? res1.data.area.split(',') : []
                    this.staffDataPermission.province = res1.data.province ? res1.data.province.split(',') : []
                    this.staffDataPermission.city = res1.data.city ? res1.data.city.split(',') : []
                    this.staffDataPermission.custom = res1.data.custom ? res1.data.custom.split(',') : []
                }
            }
        },
        async submit() {
            if (this.tab == 'menuPower') {
                //菜单权限保存
                //选中的和半选的合并后传值接口
                this.isSaveing = true
                var checkedKeys = this.$refs.menu.getCheckedNodes().concat(this.$refs.menu.getHalfCheckedNodes())
                var powerIds = []
                checkedKeys.forEach((res) => {
                    powerIds.push(res.id)
                })

                if (this.isMultiply) {
                    var data = this.staffIds.map((item) => {
                        return {
                            powerId: powerIds,
                            staffId: item,
                        }
                    })
                    var res = await this.$API.basic.staff.batchSetPowerByStaff.post({ data: data })
                    if (res && res.code == 0) {
                        this.isSaveing = false
                        this.visible = false
                        this.$message.success('操作成功')
                        this.$emit('success')
                    }
                } else {
                    var data = {
                        powerId: powerIds,
                        staffId: this.data.staffId,
                    }
                    var res = await this.$API.basic.staff.setPowerByStaff.post({ data: data })
                    if (res && res.code == 0) {
                        this.isSaveing = false
                        this.visible = false
                        this.$message.success('操作成功')
                        this.$emit('success')
                    }
                }
            } else {
                let validate = this.$refs.dataPower.validate()
                if (validate) {
                    this.$message.warning(validate)
                    return false
                } else {
                    this.isSaveing = true

                    let data = {}
                    data.id = this.staffDataPermission.id
                    data.area = this.staffDataPermission.area.join(',')
                    data.province = this.staffDataPermission.province.join(',')
                    data.city = this.staffDataPermission.city.join(',')
                    data.custom = this.staffDataPermission.custom.join(',')

                    if (this.isMultiply) {
                        var req = this.staffIds.map((item) => {
                            return { ...{ staffId: item, }, ...data }
                        })
                        var res1 = await this.$API.basic.staff.batchSetDataPower.post({ data: req })
                        if (res1 && res1.code == 0) {
                            this.isSaveing = false
                            this.visible = false
                            this.$message.success('操作成功')
                            this.$emit('success')
                        }
                    } else {
                        //数据权限保存
                        this.isSaveing = true
                        data.staffId = this.data.staffId
                        var res1 = await this.$API.basic.staff.setDataPower.post({ data: data })
                        if (res1 && res1.code == 0) {
                            this.isSaveing = false
                            this.visible = false
                            this.$message.success('操作成功')
                            this.$emit('success')
                        }
                    }
                }
            }
        },

        async getMenu() {
            var res = await this.$API.basic.power.list.post({ data: {} })
            this.menu.list = res.data.menu

            // var res = await this.$API.basic.power.list.post();
            // this.dataPowerOptions = res.data.menu
            //获取接口返回的之前选中的和半选的合并，处理过滤掉有叶子节点的key
            // this.menu.checked = ["system", "user", "user.add", "user.edit", "user.del", "directive.edit", "other", "directive"]
            // this.$nextTick(() => {
            // 	let filterKeys = this.menu.checked.filter(key => this.$refs.menu.getNode(key).isLeaf)
            // 	this.$refs.menu.setCheckedKeys(filterKeys, true)
            // })
        },
        async getDept() {
            var res = await this.$API.system.dept.list.get()
            this.data.list = res.data
            this.data.checked = []
            this.$nextTick(() => {
                let filterKeys = this.data.checked.filter((key) => this.$refs.dept.getNode(key).isLeaf)
                this.$refs.dept.setCheckedKeys(filterKeys, true)
            })
        },
        renderTreeNodeContent(h, { node, data }) {
            return h(
                'span',
                {
                    style: {
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        width: '100%'
                    }
                },
                [
                    node.label,
                    data.dataPower == 0 ?
                        h(
                            'el-button',
                            {
                                style: { marginLeft: '10px', width: '16px', height: '16px' },
                                onClick: function (e) {
                                    e.stopPropagation() // 阻止触发节点选中/展开
                                    this.handleNodeButtonClick(data)
                                }.bind(this)
                            },
                            [
                                h(data.editStatus == null || data.editStatus == 0 ? editSvg : editSvgYellow, {
                                    style: { width: '16px', height: '16px' }
                                })
                            ]
                        ) : null
                ]
            )
        },
        handleNodeButtonClick(data) {
            console.log('点击了按钮:', data)
            // 在这里执行你需要的操作，比如弹窗、删除、编辑等
            this.permissionTitle = '对' + data.meta.title + '进行数据权限设置'

            this.dialog.dataPermission = true
            this.$nextTick(() => {
                this.$refs.dataPermissionDialog.open(data, this.data.staffId, this.isMultiply, this.staffIds)
            })
        },
        //本地更新数据
        handleSaveSuccess(data, mode) {
            this.dialog.dataPermission = false
        },
        accountFilterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        //树点击事件
        accountClick(data) {
            // let orgIds = [];
            // orgIds.push(data.id);
            // var node = this.$refs.group.getNode(data);
            // this.node = node
            // this.getTree(node.data, orgIds)
            // this.params.orgIds = orgIds;
            // this.$refs.table.reload(this.params);
        },
        buildMenuMap(menuList, map) {
            for (const item of menuList) {
                map.set(item.id, item);
                if (item.children && item.children.length > 0) {
                    this.buildMenuMap(item.children, map); // 递归处理子级
                }
            }
            return map;
        },
        async del() {
            //删除数据权限
            this.delLoading = true
            var res = await this.$API.basic.staff.deleteStaffDataPower.post({ data: { staffId: this.data.staffId } })
            if (res && res.code == 0) {
                this.isSaveing = false
                this.visible = false
                this.$message.success('操作成功')
                this.$emit('success')
            }
            this.delLoading = false
        }
    }
}

</script>

<style scoped>
.treeMain {
    height: 280px;
    overflow: auto;
    border: 1px solid #dcdfe6;
    margin-bottom: 10px;
}

.fixed-height-tree {
    height: 70vh;
    /* 视口高度的 60% */
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    padding: 10px;
}
</style>
